import { createStore, createLogger, Store } from 'vuex'
import { TodoItemState } from '@/common/const'
import { TodoItem, editParams } from '@/common/interface'
import { v4 as uuidv4 } from 'uuid'
import { storage } from '@/common/utils'

const debug = process.env.NODE_ENV !== 'product'
const savePlugin = (store: Store<{todos: TodoItem[]}>) => {
  store.state.todos = storage.get('lastest_todos')
  store.subscribe((mutation, state) => {
    storage.set('lastest_todos', state.todos)
  })
}

export default createStore({
  state: {
    todos: [] as TodoItem[]
  },
  getters: {
    getDones: (state) => state.todos.filter(item => item.state === TodoItemState.DONE),
    getDeletes: (state) => state.todos.filter(item => item.state === TodoItemState.DELETE)
  },
  mutations: {
    add (state, value) {
      state.todos.push({
        id: uuidv4(),
        text: value,
        state: TodoItemState.OPEN
      })
    },
    check (state, id) {
      const index = state.todos.findIndex((item) => item.id === id)
      state.todos[index].state = state.todos[index].state === TodoItemState.DONE ? TodoItemState.OPEN : TodoItemState.DONE
    },
    delete (state, id) {
      const index = state.todos.findIndex((item) => item.id === id)
      state.todos[index].state = TodoItemState.DELETE
    },
    clearAll (state, type: TodoItemState) {
      const len: number = state.todos.length
      for (let i = 0; i < len; i++) {
        if (state.todos[i].state === type) {
          state.todos.splice(i, 1)
        }
      }
    },
    clear (state, id: string) {
      const i = state.todos.findIndex(item => item.id === id)
      state.todos.splice(i, 1)
    },
    edit (state, obj: editParams) {
      const i = state.todos.findIndex(item => item.id === obj.id)
      state.todos[i].text = obj.text
    },
    todoText: (state, id: string) => {
      console.log(id)
      const i = state.todos.findIndex(item => item.id === id)
      return i === -1 ? '' : state.todos[i].text
    }
  },
  actions: {
  },
  modules: {
  },
  plugins: debug ? [createLogger(), savePlugin] : [savePlugin]
})
